﻿@model List<Entity.NumberingRule>
@using System.Linq
@using Microsoft.AspNetCore.Mvc.Rendering
@{
    ViewData["Title"] = "编号规则管理";
    var targetFormItems = ViewBag.TargetForms as List<SelectListItem> ?? new List<SelectListItem>();
    var currentOperator = ViewData["CurrentOperator"]?.ToString() ?? "system";
}

<!-- Toast 提示容器 -->
<div id="toastContainer" class="position-fixed top-2 end-2 z-50"></div>

<!-- 搜索区域 -->
<div class="row mb-4">
    <div class="col-md-2">
        <label for="target_id" class="form-label">目标表单</label>
        <select class="form-select" id="target_id">
            <option value="">请选择</option>
            @if (targetFormItems.Any())
            {
                @foreach (var form in targetFormItems)
                {
                    <option value="@form.Value">@form.Text</option>
                }
            }
            else
            {
                <option value="-1" disabled>无目标表单数据</option>
            }
        </select>
    </div>
    <div class="col-md-3">
        <label for="number_prefix" class="form-label">编号前缀</label>
        <input type="text" class="form-control" id="number_prefix" placeholder="例如：HP">
    </div>
    <div class="col-md-3">
        <label for="time_rule" class="form-label">时间规则</label>
        <input type="text" class="form-control" id="time_rule" placeholder="例如：YYYYMM">
    </div>
    <div class="col-md-3">
        <label for="operation_time_str" class="form-label">操作时间</label>
        <input type="datetime-local" class="form-control" id="operation_time_str">
    </div>
    <div class="col-md-1 mt-4 d-flex align-items-end">
        <button type="button" class="btn btn-secondary me-2" id="resetBtn">重置</button>
        <button type="button" class="btn btn-success" id="queryBtn">查询</button>
    </div>
</div>

<!-- 功能按钮区域 -->
<div class="row mb-4">
    <div class="col-auto">
        <button type="button" class="btn btn-info me-3" id="addRuleBtn">
            <i class="fas fa-plus"></i> 添加规则
        </button>
        <button type="button" class="btn btn-primary" id="exportBtn">
            <i class="fas fa-download"></i> 导出
        </button>
    </div>
</div>

<!-- 数据表格区域 -->
<table class="table table-striped table-bordered table-hover">
    <thead class="table-light">
        <tr>
            <th>序号</th>
            <th>目标表单</th>
            <th>编号前缀</th>
            <th>时间规则</th>
            <th>流水号位数</th>
            <th>步长</th>
            <th>生成规则预览</th>
            <th>操作人</th>
            <th>操作时间</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody id="ruleTableBody">
        @if (Model != null && Model.Count > 0)
        {
            for (int i = 0; i < Model.Count; i++)
            {
                var rule = Model[i];
                // 跳过无效规则（无ID或ID<=0）
                if (rule.rule_id <= 0)
                {
                    continue;
                }

                var targetForm = targetFormItems.FirstOrDefault(f => f.Value == rule.target_id.ToString());
                var targetFormText = targetForm?.Text ?? rule.target_form ?? "";
                <tr>
                    <td>@(i + 1)</td>
                    <td>@targetFormText</td>
                    <td>@rule.number_prefix</td>
                    <td>@rule.time_rule</td>
                    <td>@rule.serial_number</td>
                    <td>@rule.step</td>
                    <td>@rule.number_production_rule</td>
                    <td>@rule.Operator</td>
                    <td>@(rule.operation_time > DateTime.MinValue ? rule.operation_time.ToString("yyyy-MM-dd HH:mm:ss") : "-")</td>
                    <td>
                        <!-- 编辑按钮 -->
                        <a href="javascript:;" class="text-success edit-btn me-3"
                           data-ruleid="@rule.rule_id"
                           data-targetform="@targetFormText"
                           data-targetformvalue="@rule.target_id"
                           data-numberprefix="@rule.number_prefix">
                            编辑
                        </a>

                        <!-- 删除按钮 -->
                        <a href="javascript:;" class="text-danger delete-btn"
                           data-ruleid="@rule.rule_id"
                           data-targetform="@targetFormText"
                           data-numberprefix="@rule.number_prefix">
                            删除
                        </a>
                    </td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="10" class="text-center py-3">暂无数据</td>
            </tr>
        }
    </tbody>
</table>

<!-- 分页控件区域 -->
<div class="row mt-4">
    <div class="col-md-6 text-muted">
        共 <span id="totalCount">0</span> 条数据，共 <span id="totalPages">0</span> 页
    </div>
    <div class="col-md-6 d-flex justify-content-end">
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0" id="pagination">
                <!-- 分页按钮由JS动态生成 -->
            </ul>
        </nav>
    </div>
</div>

<!-- 编辑/新增共用模态框 -->
<div class="modal fade" id="ruleModal" tabindex="-1" aria-labelledby="ruleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title" id="ruleModalLabel">编辑编号规则</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="ruleModalBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载表单...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除编号规则吗？</p>
                <div class="alert alert-info">
                    <strong>目标表单：</strong><span id="deleteTargetForm"></span><br>
                    <strong>编号前缀：</strong><span id="deleteNumberPrefix"></span>
                </div>
                <p class="text-danger">此操作不可恢复，请谨慎操作！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 隐藏字段 -->
<input type="hidden" id="hiddenTargetForms" value='@Json.Serialize(targetFormItems)'>
<input type="hidden" id="hiddenCurrentOperator" value="@currentOperator">

@section Scripts {
    <script>
               // 分页状态管理
        let paginationState = {
            page_index: 1,
            page_size: 10,
            total_count: 0,
            total_pages: 0
        };

        // 目标表单名称校验状态
        let isTargetFormValid = false;

        $(function () {
            // 初始化查询
            queryRules();

            // 事件绑定
            $("#queryBtn").click(() => {
                paginationState.page_index = 1;
                queryRules();
            });
            $("#resetBtn").click(resetQuery);
            $("#exportBtn").click(exportAll);
            $("#addRuleBtn").click(showAddModal);

            // 编辑按钮事件
            $(document).on("click", ".edit-btn", function () {
                const ruleId = $(this).data("ruleid");
                const targetForm = $(this).data("targetform");
                const targetFormValue = $(this).data("targetformvalue");
                const numberPrefix = $(this).data("numberprefix");
                showEditModal(ruleId, targetForm, targetFormValue, numberPrefix);
            });

            // 删除按钮事件
            $(document).on("click", ".delete-btn", function () {
                const $this = $(this);
                const ruleId = parseInt($this.data("ruleid") || 0);
                const targetForm = $this.data("targetform") || "未知";
                const numberPrefix = $this.data("numberprefix") || "未知";

                if (isNaN(ruleId) || ruleId <= 0) {
                    showToast("无效的规则ID，无法执行删除操作", false);
                    return;
                }

                showDeleteConfirmModal(ruleId, targetForm, numberPrefix);
            });
        });

        // 显示提示消息
        function showToast(message, isSuccess = true) {
            const toast = $(`
                <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="toast-header ${isSuccess ? 'bg-success text-white' : 'bg-danger text-white'}">
                        <strong class="me-auto">${isSuccess ? '成功' : '错误'}</strong>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body">${message}</div>
                </div>
            `);
            $("#toastContainer").append(toast);
            const bsToast = new bootstrap.Toast(toast[0]);
            bsToast.show();
            setTimeout(() => toast.remove(), 3000);
        }

        // 重置查询条件
        function resetQuery() {
            $("#target_id").val("");
            $("#number_prefix").val("");
            $("#time_rule").val("");
            $("#operation_time_str").val("");
            paginationState.page_index = 1;
            queryRules();
        }

               // 查询规则数据
        function queryRules() {
            const params = {
                target_id: $("#target_id").val() || null,
                number_prefix: $("#number_prefix").val(),
                time_rule: $("#time_rule").val(),
                operation_time_str: $("#operation_time_str").val(),
                 // 关键修复：参数名改为 pageIndex（驼峰），与后端一致
        pageIndex: paginationState.page_index,
        // 同步修复 pageSize 参数名（避免后续踩坑）
        pageSize: paginationState.page_size
            };

            console.log("查询参数:", params);

            // 修复：明确设置 Content-Type 为 application/json
            $.ajax({
                url: "/NumberingRule/Query",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(params),
                success: function (res) {
                    console.log("查询响应:", res);

                    if (!res.success) {
                        showToast("查询失败：" + (res.error || "未知错误"), false);
                        renderTable([]);
                        paginationState.total_count = 0;
                        paginationState.total_pages = 0;
                        renderPagination();
                        return;
                    }

                    // 更新分页状态
                    const currentPageData = res.data || [];
                    paginationState.total_count = res.totalCount || 0;
                    paginationState.total_pages = res.totalPages || 0;
                    paginationState.page_index = res.pageIndex || 1;

                    console.log("更新后的分页状态:", paginationState);
                    console.log("数据条数:", currentPageData.length);

                    renderTable(currentPageData);
                    renderPagination();
                },
                error: function (xhr, status, error) {
                    console.error("查询错误:", error);
                    console.error("状态:", status);
                    console.error("响应:", xhr.responseText);
                    showToast("请求错误：" + (xhr.responseText || "网络异常，请重试"), false);
                    renderTable([]);
                    paginationState.total_count = 0;
                    paginationState.total_pages = 0;
                    renderPagination();
                }
            });
        }

        // 渲染表格数据
        function renderTable(currentPageData) {
            const tbody = $("#ruleTableBody").empty();
            const { page_index, page_size } = paginationState;

            if (!currentPageData || currentPageData.length === 0) {
                tbody.append('<tr><td colspan="10" class="text-center py-3">暂无数据</td></tr>');
                return;
            }

            currentPageData.forEach((rule, index) => {
                if (!rule.rule_id || rule.rule_id <= 0) return;

                const globalIndex = (page_index - 1) * page_size + (index + 1);
                const operationTime = rule.operation_time
                    ? new Date(rule.operation_time).toLocaleString()
                    : "-";

                const tr = $(`
                    <tr>
                        <td>${globalIndex}</td>
                        <td>${rule.target_form || '-'}</td>
                        <td>${rule.number_prefix || '-'}</td>
                        <td>${rule.time_rule || '-'}</td>
                        <td>${rule.serial_number > 0 ? rule.serial_number : 0}</td>
                        <td>${rule.step > 0 ? rule.step : 1}</td>
                        <td>${rule.number_production_rule || '-'}</td>
                        <td>${rule.operator || '-'}</td>
                        <td>${operationTime}</td>
                        <td>
                            <a href="javascript:;" class="text-success edit-btn me-3"
                               data-ruleid="${rule.rule_id}"
                               data-targetform="${rule.target_form || ''}"
                               data-targetformvalue="${rule.target_id || ''}"
                               data-numberprefix="${rule.number_prefix || ''}">
                                编辑
                            </a>
                            <a href="javascript:;" class="text-danger delete-btn"
                               data-ruleid="${rule.rule_id}"
                               data-targetform="${rule.target_form || ''}"
                               data-numberprefix="${rule.number_prefix || ''}">
                                删除
                            </a>
                        </td>
                    </tr>
                `);
                tbody.append(tr);
            });
        } // 渲染表格数据
        function renderTable(currentPageData) {
            const tbody = $("#ruleTableBody").empty();
            const { page_index, page_size } = paginationState;

            if (!currentPageData || currentPageData.length === 0) {
                tbody.append('<tr><td colspan="10" class="text-center py-3">暂无数据</td></tr>');
                return;
            }

            currentPageData.forEach((rule, index) => {
                if (!rule.rule_id || rule.rule_id <= 0) return;

                const globalIndex = (page_index - 1) * page_size + (index + 1);
                const operationTime = rule.operation_time
                    ? new Date(rule.operation_time).toLocaleString()
                    : "-";

                const tr = $(`
                    <tr>
                        <td>${globalIndex}</td>
                        <td>${rule.target_form || '-'}</td>
                        <td>${rule.number_prefix || '-'}</td>
                        <td>${rule.time_rule || '-'}</td>
                        <td>${rule.serial_number > 0 ? rule.serial_number : 0}</td>
                        <td>${rule.step > 0 ? rule.step : 1}</td>
                        <td>${rule.number_production_rule || '-'}</td>
                        <td>${rule.operator || '-'}</td>
                        <td>${operationTime}</td>
                        <td>
                            <a href="javascript:;" class="text-success edit-btn me-3"
                               data-ruleid="${rule.rule_id}"
                               data-targetform="${rule.target_form || ''}"
                               data-targetformvalue="${rule.target_id || ''}"
                               data-numberprefix="${rule.number_prefix || ''}">
                                编辑
                            </a>
                            <a href="javascript:;" class="text-danger delete-btn"
                               data-ruleid="${rule.rule_id}"
                               data-targetform="${rule.target_form || ''}"
                               data-numberprefix="${rule.number_prefix || ''}">
                                删除
                            </a>
                        </td>
                    </tr>
                `);
                tbody.append(tr);
            });
        }

        // 渲染分页控件
        function renderPagination() {
            const pagination = $("#pagination").empty();
            const { page_index, total_pages, total_count } = paginationState;

            console.log("渲染分页 - 当前页:", page_index, "总页数:", total_pages, "总条数:", total_count);

            $("#totalCount").text(total_count || 0);
            $("#totalPages").text(total_pages || 0);

            if (!total_count || total_count === 0) {
                pagination.append(
                    $("<li>").addClass("page-item disabled").append(
                        $("<a>").addClass("page-link").text("暂无数据")
                    )
                );
                return;
            }

            // 首页按钮
            const firstPageLi = $("<li>").addClass("page-item" + (page_index === 1 ? " disabled" : ""));
            firstPageLi.append(
                $("<a>").addClass("page-link").attr("href", "javascript:void(0);").text("首页").click(function() {
                    console.log("点击首页 - 从", page_index, "到1");
                    if (page_index !== 1) {
                        paginationState.page_index = 1;
                        queryRules();
                    }
                })
            );
            pagination.append(firstPageLi);

            // 上一页按钮
            const prevPageLi = $("<li>").addClass("page-item" + (page_index === 1 ? " disabled" : ""));
            prevPageLi.append(
                $("<a>").addClass("page-link").attr("href", "javascript:void(0);").text("«").click(function() {
                    console.log("点击上一页 - 从", page_index, "到", page_index - 1);
                    if (page_index > 1) {
                        paginationState.page_index = page_index - 1;
                        queryRules();
                    }
                })
            );
            pagination.append(prevPageLi);

            // 页码按钮
            let startPage = Math.max(1, page_index - 2);
            let endPage = Math.min(total_pages, startPage + 4);

            // 调整起始页，确保显示足够的页码
            if (endPage - startPage < 4 && total_pages > 5) {
                startPage = Math.max(1, endPage - 4);
            }

            for (let i = startPage; i <= endPage; i++) {
                const pageLi = $("<li>").addClass("page-item" + (i === page_index ? " active" : ""));
                pageLi.append(
                    $("<a>").addClass("page-link").attr("href", "javascript:void(0);").text(i).click(function() {
                        console.log("点击页码 - 从", page_index, "到", i);
                        if (page_index !== i) {
                            paginationState.page_index = i;
                            queryRules();
                        }
                    })
                );
                pagination.append(pageLi);
            }

            // 下一页按钮
            const nextPageLi = $("<li>").addClass("page-item" + (page_index === total_pages ? " disabled" : ""));
            nextPageLi.append(
                $("<a>").addClass("page-link").attr("href", "javascript:void(0);").text("»").click(function() {
                    console.log("点击下一页 - 从", page_index, "到", page_index + 1);
                    if (page_index < total_pages) {
                        paginationState.page_index = page_index + 1;
                        queryRules();
                    }
                })
            );
            pagination.append(nextPageLi);

            // 末页按钮
            const lastPageLi = $("<li>").addClass("page-item" + (page_index === total_pages ? " disabled" : ""));
            lastPageLi.append(
                $("<a>").addClass("page-link").attr("href", "javascript:void(0);").text("末页").click(function() {
                    console.log("点击末页 - 从", page_index, "到", total_pages);
                    if (page_index !== total_pages) {
                        paginationState.page_index = total_pages;
                        queryRules();
                    }
                })
            );
            pagination.append(lastPageLi);
        }

        // 显示新增模态框
        function showAddModal() {
            $("#ruleModalLabel").text("添加编号规则");
            const currentOperator = $("#hiddenCurrentOperator").val();

            const formHtml = `
                <form id="addRuleForm" class="row g-4 needs-validation" novalidate>
                    <input type="hidden" name="rule_id" value="0">
                    <input type="hidden" name="current_operator" value="${currentOperator}">
                    <input type="hidden" id="hiddenTimeRule" value="YYYYMMDD">

                    <!-- 目标表单名称 -->
                    <div class="col-md-6">
                        <label for="target_form_name" class="form-label fw-semibold">
                            目标表单 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="target_form_name" name="target_form_name"
                               placeholder="例如：采购单、入库单" maxlength="50" required
                               onblur="checkTargetFormName()"
                               oninput="resetTargetFormValidation()">
                        <div class="invalid-feedback" id="targetFormEmptyError">请输入目标表单名称</div>
                        <div class="invalid-feedback" id="targetFormDuplicateError" style="display: none; color: #dc3545;">该表单名称已存在，请更换</div>
                        <div class="valid-feedback" id="targetFormValidError" style="display: none; color: #198754;">表单名称可用</div>
                        <small class="form-text text-muted">输入新的目标表单名称，系统将自动创建</small>
                    </div>

                    <!-- 编号前缀 -->
                    <div class="col-md-6">
                        <label for="rule_prefix" class="form-label fw-semibold">
                            编号前缀 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="rule_prefix" name="rule_prefix"
                               placeholder="例如：PO、IN" maxlength="10" required
                               oninput="updateAddPreview()">
                        <div class="invalid-feedback">请输入1-10位的编号前缀</div>
                    </div>

                    <!-- 时间规则 -->
                    <div class="col-12">
                        <label class="form-label fw-semibold d-block">
                            时间规则组成 <span class="text-danger">*</span>
                        </label>
                        <div class="row g-3">
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeYear"
                                           data-time-code="YYYY" checked onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeYear">年(YYYY)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeMonth"
                                           data-time-code="MM" checked onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeMonth">月(MM)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeDay"
                                           data-time-code="DD" checked onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeDay">日(DD)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeHour"
                                           data-time-code="HH" onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeHour">时(HH)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeMinute"
                                           data-time-code="mm" onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeMinute">分(mm)</label>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input time-checkbox" type="checkbox" id="addIncludeSecond"
                                           data-time-code="ss" onchange="updateAddPreview()">
                                    <label class="form-check-label" for="addIncludeSecond">秒(ss)</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 流水号位数 -->
                    <div class="col-md-6">
                        <label for="serial_number_length" class="form-label fw-semibold">
                            流水号位数 <span class="text-danger">*</span>
                        </label>
                        <input type="number" class="form-control" id="serial_number_length" name="serial_number_length"
                               value="3" min="1" max="10" required
                               oninput="this.value = Math.max(1, Math.min(10, this.value)); updateAddPreview()">
                        <div class="invalid-feedback">请输入1-10位的流水号位数</div>
                    </div>

                    <!-- 步长 -->
                    <div class="col-md-6">
                        <label for="step" class="form-label fw-semibold">
                            步长 <span class="text-danger">*</span>
                        </label>
                        <input type="number" class="form-control" id="step" name="step"
                               value="1" min="1" max="100" required
                               oninput="this.value = Math.max(1, Math.min(100, this.value)); updateAddPreview()">
                        <div class="invalid-feedback">请输入1-100的步长</div>
                    </div>

                    <!-- 规则预览 -->
                    <div class="col-12">
                        <label class="form-label fw-semibold d-block">规则预览</label>
                        <div class="card bg-light border">
                            <div class="card-body">
                                <input type="text" class="form-control" id="addRulePreview"
                                       value="PO20240520001" readonly style="font-weight: 500;">
                            </div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="col-12 d-flex justify-content-end gap-3 pt-2">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveAddRule()">保存规则</button>
                    </div>
                </form>
            `;

            $("#ruleModalBody").html(formHtml);
            const modal = new bootstrap.Modal(document.getElementById("ruleModal"));
            modal.show();

            // 重置校验状态
            isTargetFormValid = false;
            setTimeout(updateAddPreview, 100);
        }

        // 重置目标表单校验状态
        function resetTargetFormValidation() {
            isTargetFormValid = false;
            $("#targetFormDuplicateError").hide();
            $("#targetFormValidError").hide();
            $("#targetFormEmptyError").hide();
        }

        // 检查目标表单名称是否重复
        function checkTargetFormName() {
            const targetFormName = $("#target_form_name").val().trim();
            const duplicateError = $("#targetFormDuplicateError");
            const validError = $("#targetFormValidError");
            const emptyError = $("#targetFormEmptyError");

            if (!targetFormName) {
                duplicateError.hide();
                validError.hide();
                emptyError.show();
                isTargetFormValid = false;
                return;
            }

            $.get(`/NumberingRule/CheckTargetFormExists?target_form_name=${encodeURIComponent(targetFormName)}`)
                .done(function(data) {
                    emptyError.hide();
                    if (data.exists) {
                        duplicateError.show();
                        validError.hide();
                        isTargetFormValid = false;
                    } else {
                        duplicateError.hide();
                        validError.show();
                        isTargetFormValid = true;
                    }
                })
                .fail(function() {
                    showToast("校验表单名称失败，请重试", false);
                    isTargetFormValid = false;
                });
        }

        // 更新新增表单预览
        function updateAddPreview() {
            const prefix = $("#rule_prefix").val().trim() || "";

            let timeRule = "";
            $(".time-checkbox:checked").each(function() {
                timeRule += $(this).data("time-code") || "";
            });
            timeRule = timeRule || "YYYYMMDD";
            $("#hiddenTimeRule").val(timeRule);

            const now = new Date();
            let timeValue = "";
            if (timeRule.includes("YYYY")) timeValue += now.getFullYear();
            if (timeRule.includes("MM")) timeValue += (now.getMonth() + 1).toString().padStart(2, "0");
            if (timeRule.includes("DD")) timeValue += now.getDate().toString().padStart(2, "0");
            if (timeRule.includes("HH")) timeValue += now.getHours().toString().padStart(2, "0");
            if (timeRule.includes("mm")) timeValue += now.getMinutes().toString().padStart(2, "0");
            if (timeRule.includes("ss")) timeValue += now.getSeconds().toString().padStart(2, "0");

            const serialLength = parseInt($("#serial_number_length").val()) || 3;
            const step = parseInt($("#step").val()) || 1;
            const serialValue = step.toString().padStart(serialLength, '0');

            $("#addRulePreview").val(`${prefix}${timeValue}${serialValue}`);
        }

        // 保存新增规则
        function saveAddRule() {
            const form = $("#addRuleForm")[0];
            if (!form.checkValidity()) {
                $("#addRuleForm").addClass("was-validated");
                return;
            }

            // 检查目标表单名称是否通过校验
            if (!isTargetFormValid) {
                showToast("请先完成目标表单名称的唯一性校验", false);
                return;
            }

            const ruleData = {
                target_form_name: $("#target_form_name").val().trim(),
                rule_prefix: $("#rule_prefix").val().trim(),
                serial_number_length: parseInt($("#serial_number_length").val()),
                step: parseInt($("#step").val()),
                time_rule: $("#hiddenTimeRule").val(),
                production_rule: $("#addRulePreview").val()
            };

            $.ajax({
                url: "/NumberingRule/AddBoth",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(ruleData),
                success: function(res) {
                    if (res.success) {
                        showToast("添加规则成功！");
                        const modal = bootstrap.Modal.getInstance(document.getElementById("ruleModal"));
                        modal.hide();
                        queryRules();
                    } else {
                        showToast("添加失败：" + (res.message || "未知错误"), false);
                    }
                },
                error: function(xhr) {
                    showToast("请求错误：" + (xhr.responseText || "网络异常"), false);
                }
            });
        }

        // 显示编辑模态框
        function showEditModal(ruleId, targetForm, targetFormValue, numberPrefix) {
            if (!ruleId || ruleId <= 0) {
                showToast("无效的规则ID，无法编辑", false);
                return;
            }

            $("#ruleModalLabel").text("编辑编号规则");

            const encodedTargetForm = encodeURIComponent(targetForm || "");
            const encodedTargetFormValue = encodeURIComponent(targetFormValue || "");
            const encodedNumberPrefix = encodeURIComponent(numberPrefix || "");
            const url = `/NumberingRule/EditPartial?rule_id=${ruleId}&target_form=${encodedTargetForm}&target_form_value=${encodedTargetFormValue}&number_prefix=${encodedNumberPrefix}`;

            $.get(url)
                .done(function(html) {
                    $("#ruleModalBody").html(html);
                    const modal = new bootstrap.Modal(document.getElementById("ruleModal"));
                    modal.show();
                })
                .fail(function(xhr) {
                    $("#ruleModalBody").html(`
                        <div class="alert alert-danger" role="alert">
                            加载表单失败：${xhr.responseText || "服务器异常"}
                        </div>
                    `);
                    const modal = new bootstrap.Modal(document.getElementById("ruleModal"));
                    modal.show();
                });
        }

        // 导出全部数据
        function exportAll() {
            const params = {
                target_id: $("#target_id").val() || null,
                number_prefix: $("#number_prefix").val(),
                time_rule: $("#time_rule").val(),
                operation_time_str: $("#operation_time_str").val()
            };

            const queryString = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== null && value !== undefined && value !== '') {
                    queryString.append(key, value);
                }
            });

            window.location.href = `/NumberingRule/Export?${queryString.toString()}`;
        }

        // 显示删除确认模态框
        function showDeleteConfirmModal(ruleId, targetForm, numberPrefix) {
            if (!ruleId || ruleId <= 0) {
                showToast("无效的规则ID，无法删除", false);
                return;
            }

            $("#deleteTargetForm").text(targetForm || "未知");
            $("#deleteNumberPrefix").text(numberPrefix || "未知");
            $("#deleteConfirmModal").data("rule_id", ruleId);

            $("#confirmDeleteBtn").off("click").on("click", function() {
                const currentRuleId = $("#deleteConfirmModal").data("rule_id");
                deleteRule(currentRuleId);
            });

            const modal = new bootstrap.Modal(document.getElementById("deleteConfirmModal"));
            modal.show();
        }

        // 执行删除操作
        function deleteRule(ruleId) {
            if (!ruleId || ruleId <= 0) {
                showToast("规则ID无效，请刷新页面重试", false);
                const modal = bootstrap.Modal.getInstance(document.getElementById("deleteConfirmModal"));
                if (modal) modal.hide();
                return;
            }

            const $confirmBtn = $("#confirmDeleteBtn");
            const originalText = $confirmBtn.text();
            $confirmBtn.prop("disabled", true).text("删除中...");

            $.ajax({
                url: "/NumberingRule/Delete",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ rule_id: ruleId }),
                success: function(res) {
                    $confirmBtn.prop("disabled", false).text(originalText);

                    if (res.success) {
                        showToast("删除成功！");
                        const modal = bootstrap.Modal.getInstance(document.getElementById("deleteConfirmModal"));
                        if (modal) modal.hide();
                        queryRules();
                    } else {
                        showToast("删除失败：" + (res.message || "未知错误"), false);
                    }
                },
                error: function(xhr) {
                    $confirmBtn.prop("disabled", false).text(originalText);
                    showToast("请求错误：" + (xhr.responseText || "网络异常"), false);
                }
            });
        }

    </script>
}
